#ifndef GAME_PLATFORM_H
#define GAME_PLATFORM_H
#include <malloc.h>
#include <cfloat>
#include <cstdint>
#include <windows.h>
#include <gl/gl.h>

// #include "game_config.h"

#define introspect(IGNORED)
#define counter_pointer(IGNORED)
#define MAX_CONTROLLER_COUNT 5
#define BITMAP_BYTES_PER_PIEXLE 4

// 如果没有定义 COMPILER_MSVC，则将其定义为 0
#if !defined(COMPILER_MSVC)
#define COMPILER_MSVC 0
#endif

// 如果没有定义 COMPILER_LLVM，则将其定义为 0
#if !defined(COMPILER_LLVM)
#define COMPILER_LLVM 0
#endif

// 如果既没有定义 COMPILER_MSVC，也没有定义 COMPILER_LLVM，则根据编译器类型自动设置
#if !COMPILER_MSVC && !COMPILER_LLVM
// 检查是否为 Microsoft Visual C++ 编译器
#if _MSC_VER
// 如果是，定义 COMPILER_MSVC 为 1
#undef COMPILER_MSVC
#define COMPILER_MSVC 1
#else
// 如果不是，认为是 LLVM 编译器，定义 COMPILER_LLVM 为 1
#undef COMPILER_LLVM
#define COMPILER_LLVM 1
#endif
#endif

// 如果使用的是 Microsoft Visual C++ 编译器（COMPILER_MSVC 为 1）
#if COMPILER_MSVC
// 包含 MSVC 特有的内联函数库，提供位扫描函数等
#include <intrin.h>
// 向编译器指示 `_BitScanForward` 函数是一个内联函数，优化性能
#pragma intrinsic(_BitScanForward)
#endif

#define internal static         // 用于定义内翻译单元内部函数
#define local_persist static    // 局部静态变量
#define global_variable static  // 全局变量
#define Pi32 3.14159265359f
#define Tau32 6.28318530717958647692528676655900576839433879875021f
#define Uint16Maximum 65535
#define Real32Maximum FLT_MAX
#define Real32Minimum -FLT_MAX

typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
// 定义用于内存索引的类型，使用 `size_t` 表示内存大小
// sizeof(size_t) = 8
typedef uint64_t memory_index;
// 将 uintptr_t 类型重新命名为 uintptr
// uintptr_t 是一个无符号整数类型，能够存储指针值
// 它通常用于将指针转换为整数，并进行无符号算术或位运算
typedef uintptr_t uintptr;

// 将 intptr_t 类型重新命名为 intptr
// intptr_t 是一个有符号整数类型，能够存储指针值
// 它允许存储负数，并且常用于有符号算术操作的场景
typedef intptr_t intptr;

typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef int32_t bool32;

typedef float real32;
typedef double real64;

#if COMPILE_MSVC
#define CompletePreviousReadsBeforeFutureReads _ReadBarrier()
#define CompletePreviousWriteBeforeFutureWrites _WriteBarrier()
inline uint32 AtomicCompareExchangeUInt32(uint32 volatile *Value, uint32 New, uint32 Expected) {
    uint32 Result = _InterlockedCompareExchange((volatile long *)Value, New, Expected);
    return Result;
}
inline uint64 AtomicExchangeUInt64(uint64 volatile *Value, uint64 New) {
    uint64 Result = _InterlockedExchange64((__int64 volatile *)Value, New);
    return Result;
}

inline uint64 AtomicAddU64(uint64 volatile *Value, uint64 Added) {
    uint64 Result = _InterlockedExchangeAdd64((__int64 volatile *)Value, Added);
    return Result;
}

inline uint32 AtomicAddU32(uint32 volatile *Value, uint32 Added) {
    uint32 Result = _InterlockedExchangeAdd((long volatile *)Value, Added);
    return Result;
}

#elif COMPILER_LLVM
#define CompletePreviousWriteBeforeFutureWrites asm volatile("" ::: "memory")
inline uint32 AtomicCompareExchangeUInt32(uint32 volatile *Value, uint32 New, uint32 Expected) {
    uint32 Result = __sync_val_compare_and_swap((volatile long *)Value, New, Expected);
    return Result;
}
inline uint64 AtomicExchangeUInt64(uint64 volatile *Value, uint64 New) {
    uint64 Result = __sync_lock_test_and_set(Value, New);
    return Result;
}

inline uint64 AtomicAddU64(uint64 volatile *Value, uint64 Added) {
    uint64 Result = __sync_fetch_and_add(Value, Added);
    return Result;
}
#else
#define CompletePreviousWriteBeforeFutureWrites
#endif

/*
GAME_INTERNAL:
  0 - 构建用于公开发布，代码将被用于正式发布版本，可能会进行优化和移除调试代码。
  1 - 构建仅供开发者使用，代码包含调试信息和开发时需要的额外功能。
GAME_SLOW:
  0 - 不允许慢代码，代码需要在生产环境中保持高效。
  1 -
允许慢代码(调试)，在开发和调试阶段允许一些效率较低的代码，例如用于调试的断言。
*/

#if GAME_SLOW  // 如果允许慢代码 (即在调试阶段)
#define Assert(Expression)        \
    if (!(Expression)) {          \
        (*(volatile int *)0 = 0); \
    }
#else
#define Assert(Expression)
#endif

#define InvalidCodePath Assert(!"InvalidCodePath")
#define InvalidDefaultCase \
    default: {             \
        InvalidCodePath;   \
    } break;

// 将给定的值转换为千字节（1024 字节）
#define Kilobytes(Value) ((Value) * 1024LL)

// 将给定的值转换为兆字节（1024 * 1024 字节）
#define Megabytes(Value) (Kilobytes(Value) * 1024LL)

// 将给定的值转换为吉字节（1024 * 1024 * 1024 字节）
#define Gibabytes(Value) (Megabytes(Value) * 1024LL)

// 将给定的值转换为太字节（1024 * 1024 * 1024 * 1024 字节）
#define Terabytes(Value) (Gibabytes(Value) * 1024LL)

#define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0]))
inline uint32 SafeTruncateUInt64(uint64 Value) {
    // 确保传入的 64 位值不会超出 32 位的最大值
    Assert(Value <= 0xFFFFFFFF);
    uint32 Result = (uint32)Value;  // 安全地将 64 位值截断为 32 位
    return Result;
}

inline uint16 SafeTruncateUInt16(int32 Value) {
    // 确保传入的 64 位值不会超出 32 位的最大值
    Assert(Value <= 65535);
    Assert(Value >= 0);
    uint16 Result = (uint16)Value;
    return Result;
}

inline int16 SafeTruncateInt16(int32 Value) {
    Assert(Value <= 32767);
    Assert(Value >= -32768);
    int16 Result = (int16)Value;
    return Result;
}

#if GAME_INTERNAL

/*
  以下结构体和操作仅用于游戏的内部版本，
  在正式发布的版本中不应使用！

  这些操作是阻塞的，并且写入过程不防止数据丢失。
  主要用于开发和调试阶段。
*/

struct debug_read_file_result {
    uint32 ContentsSize;  // 文件内容的大小（以字节为单位）
    void *Contents;       // 指向文件内容的内存指针
};

struct debug_executing_process {
    uint64 OSHandle;
};

struct debug_process_state {
    bool32 StartedSuccessfully;
    bool32 IsRunning;
    int32 ReturnCode;
};

// 读取整个文件内容到内存
#define DEBUG_PLATFORM_READ_ENTIRE_FILE(name) debug_read_file_result name(const char *Filename)
typedef DEBUG_PLATFORM_READ_ENTIRE_FILE(debug_platform_read_entire_file);

// 释放文件读取的内存
#define DEBUG_PLATFORM_FREE_FILE_MEMORY(name) void name(void *Memory)
typedef DEBUG_PLATFORM_FREE_FILE_MEMORY(debug_platform_free_file_memory);

// 将内存内容写入文件
#define DEBUG_PLATFORM_WRITE_ENTIRE_FILE(name) \
    void *name(const char *Filename, uint64 MemorySize, void *Memory)
typedef DEBUG_PLATFORM_WRITE_ENTIRE_FILE(debug_platform_write_entire_file);

#define DEBUG_PLATFORM_EXECUTE_SYSTEM_COMMAND(name) \
    debug_executing_process name(const char *Path, const char *Command, char *CommandLine)
typedef DEBUG_PLATFORM_EXECUTE_SYSTEM_COMMAND(debug_platform_execute_system_command);

#define DEBUG_PLATFORM_CLOSE_FILE_HANDLE(name) void name(void *FileHandle)
typedef DEBUG_PLATFORM_CLOSE_FILE_HANDLE(debug_platform_close_file_handle);

#define DEBUG_PLATFORM_GET_PROCESS_STATE(name) \
    debug_process_state name(debug_executing_process Process)
typedef DEBUG_PLATFORM_GET_PROCESS_STATE(debug_platform_get_process_state);

#endif

#if 0
enum {
    DebugCycleCounter_GameUpdateAndRender,   // 0
    DebugCycleCounter_RenderGroupToOutput,   // 1
    DebugCycleCounter_DrawRectangleSlowly,   // 2
    DebugCycleCounter_ProcessPixel,          // 3
    DebugCycleCounter_DrawRectangleQuickly,  // 4
    DebugCycleCounter_DrawBitMap,            // 5
    DebugCycleCounter_Count,

};
struct debug_cycle_counter {
    uint64 CycleCount;
    uint32 HitCount;
    const char *str[256] = {
        "DebugCycleCounter_GameUpdateAndRender",  // 0
        "DebugCycleCounter_RenderGroupToOutput",  // 1
        "DebugCycleCounter_DrawRectangleSlowly",  // 2
        "DebugCycleCounter_ProcessPixel",         // 3
        "DebugCycleCounter_DrawRectangleQuickly"  // 4
    };
};
#endif

typedef struct platform_file_handle {
    //
    bool32 NoErrors;
    void *Platform;
} platform_file_handle;
typedef struct platform_file_group {
    uint32 FileCount;
    void *Platform;
} platform_file_group;

enum platform_file_type {
    PlatformFileType_AssetFile,
    PlatformFileType_SaveGameFile,
    PlatformFileType_Count,
};

#define PLATFORM_GET_ALL_FILE_OF_TYPE_BEGIN(name) platform_file_group name(platform_file_type Type)
typedef PLATFORM_GET_ALL_FILE_OF_TYPE_BEGIN(platform_get_all_files_of_type_begin);

#define PLATFORM_GET_ALL_FILE_OF_TYPE_END(name) void name(platform_file_group *FileGroup)
typedef PLATFORM_GET_ALL_FILE_OF_TYPE_END(platform_get_all_files_of_type_end);

#define PLATFORM_OPEN_FILE(name) platform_file_handle name(platform_file_group *FileGroup)
typedef PLATFORM_OPEN_FILE(platform_open_next_file);

#define PLATFORM_READ_DATA_FROM_FILE(name) \
    void name(platform_file_handle *Source, uint64 Offset, uint64 Size, void *Dest)
typedef PLATFORM_READ_DATA_FROM_FILE(platform_read_data_from_file);

#define PLATFORM_FILE_ERROR(name) void name(platform_file_handle *Handle, const char *Message)
typedef PLATFORM_FILE_ERROR(platform_file_error);

#define PLATFORM_ALLOCATE_MEMORY(name) void *name(memory_index Size)
typedef PLATFORM_ALLOCATE_MEMORY(platform_allocate_memory);

#define PLATFORM_DEALLOCATE_MEMORY(name) void name(void *Memory)
typedef PLATFORM_DEALLOCATE_MEMORY(platform_deallocate_memory);
#define PlatformNoFileErrors(Handle) ((Handle)->NoErrors)

struct platform_work_queue;
#define PLATFORM_WORK_QUEUE_CALLBACK(name) void name(platform_work_queue *Queue, void *Data)
typedef PLATFORM_WORK_QUEUE_CALLBACK(platform_work_queue_callback);
typedef void platform_add_entry(platform_work_queue *Queue, platform_work_queue_callback *Callback,
                                void *Data);
typedef void platform_complete_all_work(platform_work_queue *Queue);
typedef void platform_opengl_render(struct render_group *RenderGroup,
                                    struct loaded_bitmap *OutputTarget);

typedef struct platform_api {
    platform_add_entry *AddEntry;
    platform_complete_all_work *CompleteAllWork;

    platform_get_all_files_of_type_begin *GetAllFilesOfTypeBegin;
    platform_get_all_files_of_type_end *GetAllFilesOfTypeEnd;
    platform_open_next_file *OpenNextFile;
    platform_read_data_from_file *ReadDataFromFile;
    platform_file_error *FileError;

    platform_allocate_memory *AllocateMemory;
    platform_deallocate_memory *DeallocateMemory;
#if GAME_INTERNAL
    // 指向临时存储的指针，用于存储短期的数据，如帧缓冲、临时计算等。
    debug_platform_read_entire_file *DEBUGPlatformReadEntireFile;
    debug_platform_free_file_memory *DEBUGPlatformFreeFileMemory;
    debug_platform_write_entire_file *DEBUGPlatformWriteEntireFile;
    debug_platform_execute_system_command *DEBUGPlatformExecuteSystemCommand;
    debug_platform_close_file_handle *DEBUGPlatformCloseFileHandle;
    debug_platform_get_process_state *DEBUGPlatformGetProcessState;
#endif  // GAME_INTERNAL
} platform_api;
struct ticket_mutex {
    uint64 volatile Ticket;
    uint64 volatile Serving;
};
inline void BeginTicketMutex(ticket_mutex *Mutex) {
    uint64 Ticket = AtomicAddU64(&Mutex->Ticket, 1);
    while (Ticket != Mutex->Serving) _mm_pause();
}
inline void EndTicketMutex(ticket_mutex *Mutex) {  //
    AtomicAddU64(&Mutex->Serving, 1);
}
struct platform_texture_op_queue {
    ticket_mutex Mutex;
    struct texture_op *First;
    texture_op *Last;
    texture_op *FirstFree;
};

struct game_memory {
    bool32 Isinitialized;  // 记录内存是否已经初始化。类型 `bool32` 是一个 32
                           // 位布尔值类型（通常是定义为 `typedef bool bool32`
                           // 或类似类型别名）。
    size_t PermanentStorageSize;  // 永久存储的大小，使用 `uint64`（64
                                  // 位无符号整数）来表示，允许存储较大的数值。
    size_t TransientStorageSize;  // 临时存储的大小，也是用 `uint64` 表示。
    void *PermanentStorage;
    // 指向永久存储的指针，通常用于存储游戏的长期数据，如保存文件、配置文件等。
    void *TransientStorage;

    uint64 DebugStorageSize;
    void *DebugStorage;
    bool32 ExecutableReloaded;

    struct platform_work_queue *RenderQueue;
    platform_work_queue *HighPriorityQueue;
    platform_work_queue *LowPriorityQueue;
    platform_texture_op_queue TextureOpQueue;
#if GAME_INTERNAL
    struct debug_table *DebugTable;
#endif

    platform_api PlatformAPI;
};

#if GAME_INTERNAL
struct game_memory;
extern game_memory *DebugGlobalMemory;
#endif
#define PointerToUint32(Pointer) ((uint32)(uintptr_t)(Pointer))
#define Uint32ToPointer(type, Value) (type *)((memory_index)Value)
#define OffsetOf(type, Member) (uintptr_t) & (((type *)0)->Member)

struct debug_table;
struct game_input;
struct game_offscreen_buffer;
#define DEBUG_GAME_FRAME_END(name) \
    void name(game_memory *Memory, game_input *Input, struct game_render_commands *Commands)
typedef DEBUG_GAME_FRAME_END(debug_game_frame_end);
#if GAME_INTERNAL
#define TIMED_BLOCK(Name, ...) TIMED_BLOCK_(DEBUG_NAME(Name), __COUNTER__, __VA_ARGS__)
#define TIMED_BLOCK_(GUID, Number, ...) TIMED_BLOCK__(GUID, Number, __VA_ARGS__)
#define TIMED_BLOCK__(GUID, Number, ...) timed_block TimedBlock_##Number(GUID, __VA_ARGS__)
#define TIMED_FUNCTION() TIMED_BLOCK_(DEBUG_NAME(__FUNCTION__), __VA_ARGS__)
#else

#define TIMED_BLOCK(BlockName, ...)
#define TIMED_BLOCK_(BlockName, Number, ...)
#define TIMED_BLOCK__(BlockName, Number, ...)
#define TIMED_FUNCTION(...)
#endif
struct debug_record {
    const char *FileName;
    const char *BlockName;

    uint32 LineNumber;
    uint32 Reserved;
};
enum debug_type {
    DebugType_Unknown,
    DebugType_FrameMarker,
    DebugType_BeginBlock,
    DebugType_EndBlock,
    DebugType_OpenDataBlock,
    DebugType_CloseDataBlock,
    // DebugType_MarkDebugValue,

    DebugType_bool32,
    DebugType_real32,
    DebugType_uint32,
    DebugType_int32,
    DebugType_v2,
    DebugType_v3,
    DebugType_v4,
    DebugType_rectangle2,
    DebugType_rectangle3,
    DebugType_bitmap_id,
    DebugType_sound_id,
    DebugType_font_id,
    DebugType_memory_arena_p,

    DebugType_BitmapDisplay,
    DebugType_ThreadIntervalGraph,
    DebugType_LastFrameInfo,
    DebugType_DebugMemoryInfo,
    DebugType_FrameSlider,
    DebugType_FrameBarGraph,
    DebugType_TopClocksList,
    DebugType_ArenaOccupancy,
};

union v2 {
    struct {
        real32 x, y;  // 向量的 x 和 y 分量
    };
    struct {
        real32 u, v;
    };
    real32 E[2];
};
// 定义三维向量 v3，使用联合体表示，以支持多种访问方式
union v3 {
    // 第一种结构体形式，提供 x、y、z 分量的直接访问，常用于几何向量计算
    struct {
        real32 x, y, z;
    };
    // 第二种结构体形式，提供 r、g、b 分量的直接访问，常用于颜色表示
    struct {
        real32 r, g, b;
    };
    struct {
        real32 u, v, w;
    };

    struct {
        v2 xy;
        real32 Ignored0_;
    };
    struct {
        real32 Ignored1_;
        v2 yz;
    };
    struct {
        v2 uv;
        real32 Ignored2_;
    };
    struct {
        real32 Ignored3_;
        v2 vw;
    };
    // 数组形式，提供通过索引访问的能力，支持访问所有三个分量
    real32 E[3];
};

// 定义四维向量 v4，使用联合体表示，以支持多种访问方式
union v4 {
    // 第一种结构体形式，提供 x、y、z、w 分量的直接访问，常用于齐次坐标或四维向量
    struct {
        union {
            v3 xyz;
            struct {
                real32 x, y, z;
            };
        };
        real32 w;
    };
    // 第二种结构体形式，提供 r、g、b、a 分量的直接访问，常用于带透明度的颜色表示
    struct {
        union {
            v3 rgb;
            struct {
                real32 r, g, b;
            };
        };
        real32 a;
    };
    struct {
        v2 xy;
        real32 Ignored0_;
        real32 Ignored1_;
    };
    struct {
        real32 Ignored2_;
        v2 yz;
        real32 Ignored3_;
    };
    struct {
        real32 Ignored4_;
        real32 Ignored5_;
        v2 zw;
    };

    // 数组形式，提供通过索引访问的能力，支持访问所有四个分量
    real32 E[4];
};

// 定义一个矩形结构体，包含最小点(Min)和最大点(Max)
introspect(category : "math") struct rectangle2 {
    v2 Min;  // 矩形的最小点（左下角）
    v2 Max;  // 矩形的最大点（右上角）
};
introspect(category : "math") struct rectangle3 {
    v3 Min;  // 矩形的最小点（左下角）
    v3 Max;  // 矩形的最大点（右上角）
};

#pragma pack(push, 1)

struct bitmap_id {
    uint32 Value;
};
struct sound_id {
    uint32 Value;
};

struct font_id {
    uint32 Value;
};
#pragma pack(pop)
struct debug_id {
    void *Value[2];
};
struct memory_arena;
typedef memory_arena *memory_arena_p;
struct debug_event {
    uint64 Clock;
    const char *GUID;
    uint32 LineNumber;
    uint16 ThreadID;
    uint16 CoreIndex;
    debug_type Type;
    union {
        debug_id DebugID;
        debug_event *Value_debug_event;
        bool32 Value_bool32;
        uint32 Value_uint32;
        int32 Value_int32;
        real32 Value_real32;
        v2 Value_v2;
        v3 Value_v3;
        v4 Value_v4;
        rectangle2 Value_rectangle2;
        rectangle3 Value_rectangle3;
        bitmap_id Value_bitmap_id;
        sound_id Value_sound_id;
        font_id Value_font_id;
        memory_arena_p Value_memory_arena_p;
    };
};

struct debug_table {
    debug_event EditEvent;
    uint32 CurrentEventArrayIndex;
    uint64 volatile EventArrayIndex_EventIndex;
    uint32 RecordIncrement;
    debug_event Events[2][32 * 65536];
};

extern debug_table *GlobalDebugTable;

inline uint32 GetThreadID(void) {
    uint32 ThreadID;
    uint8 *ThreadLocalStorage = (uint8 *)__readgsqword(0x30);
#if defined(__APPLE__)
    asm("mov %%gs:0x00,%0" : "=r"(ThreadID));
#elif (__i386__)
    asm("mov %%gs:0x08,%0" : "=r"(ThreadID));
#elif (__x86_64__)
    ThreadID = *(uint32 *)(ThreadLocalStorage + 0x48);
#else
#error Unsupported architecture
#endif
    return ThreadID;
}

#define UniqueFileCounterString__(A, B, C, D) A "|" #B "|" #C "|" D
#define UniqueFileCounterString_(A, B, C, D) UniqueFileCounterString__(A, B, C, D)
#define DEBUG_NAME(Name) UniqueFileCounterString_(__FILE__, __LINE__, __COUNTER__, Name)
#define DebugSetEventRecording(Enabled) (GlobalDebugTable->RecordIncrement = (Enabled) ? 1 : 0)

// 【common】 a. 通常的, 共同的, 通俗的, 公共的 [计] 公用块
#define RecordDebugEvent(EventType, GUIDInit)                                                  \
    Assert(((uint64)(&GlobalDebugTable->EventArrayIndex_EventIndex) & 0x4) == 0);              \
    uint64 ArrayIndex_EventIndex = AtomicAddU64(&GlobalDebugTable->EventArrayIndex_EventIndex, \
                                                GlobalDebugTable->RecordIncrement);            \
    uint32 EventIndex = ArrayIndex_EventIndex & 0xFFFF'FFFF;                                   \
    Assert(EventIndex < ArrayCount(GlobalDebugTable->Events[0]));                              \
    debug_event *Event = GlobalDebugTable->Events[ArrayIndex_EventIndex >> 32LL] + EventIndex; \
    Event->ThreadID = (uint16)GetThreadID();                                                   \
    Event->Clock = __rdtsc();                                                                  \
    Event->Type = EventType;                                                                   \
    int CoreIndex;                                                                             \
    __rdtscp((unsigned int *)&CoreIndex);                                                      \
    Event->CoreIndex = (uint16)CoreIndex;                                                      \
    Event->GUID = GUIDInit

#define FRAME_MARKER(SecondsElapsedInit)                                     \
    {                                                                        \
        RecordDebugEvent(DebugType_FrameMarker, DEBUG_NAME("Frame Marker")); \
        Event->Value_real32 = SecondsElapsedInit;                            \
    }

#if GAME_INTERNAL
#define BEGIN_BLOCK_(GUID) \
    { RecordDebugEvent(DebugType_BeginBlock, GUID); }

#define END_BLOCK_(GUID) \
    { RecordDebugEvent(DebugType_EndBlock, GUID); }

#define BEGIN_BLOCK(Name) BEGIN_BLOCK_(DEBUG_NAME(Name))

#define END_BLOCK() END_BLOCK_(DEBUG_NAME("END_BLOCK_"));
#else

#define BEGIN_BLOCK(Name)
#define END_BLOCK(Name)
#define BEGIN_BLOCK_(Counter, FileNameInit, LineNumberInit, BlockNameInit) \
    {                                                                      \
        (void)Counter, (void)FileNameInit;                                 \
        (void)LineNumberInit;                                              \
        (void)BlockNameInit;                                               \
    }
#define END_BLOCK_(Counter) \
    { (void)Counter; }
#endif

struct manual_timed_block {
    int Counter;
};
struct timed_block {
    int Counter;
    timed_block(const char *GUID, uint32 HitCountInit = 1) {
        (void)HitCountInit;
        BEGIN_BLOCK_(GUID);
    }
    ~timed_block() {  //
        END_BLOCK();
    }
};

internal int StringLength(const char *String) {
    // 计算并返回 C 风格字符串的长度（不包括空终止符 '\0'）。
    int Count = 0;  // 初始化计数器，用于记录字符串中的字符数。
    // 遍历字符串的每个字符，直到遇到空终止符 '\0'。
    while (*String++) {
        ++Count;  // 每读取一个字符，就将计数器递增。
    }
    return Count;  // 返回字符串的长度（字符总数，不包括空终止符）。
}

internal void CatStrings(size_t SourceACount, char *SourceA,        //
                         size_t SourceBCount, const char *SourceB,  //
                         size_t DestCount, char *Dest) {
    (void)DestCount;
    // 将 SourceA 和 SourceB 两个字符串拼接到目标字符串 Dest 中，并在末尾添加空终止符 '\0'。

    // 遍历 SourceA 的字符并复制到 Dest
    for (size_t Index = 0; Index < SourceACount; Index++) {
        *Dest++ = *SourceA++;  // 将 SourceA 的当前字符复制到 Dest，并递增指针以移动到下一个字符。
    }

    // 遍历 SourceB 的字符并复制到 Dest
    for (size_t Index = 0; Index < SourceBCount; ++Index) {
        *Dest++ = *SourceB++;  // 将 SourceB 的当前字符复制到 Dest，并递增指针以移动到下一个字符。
    }

    // 添加空终止符 '\0' 以确保 Dest 成为一个有效的 C 风格字符串。
    *Dest++ = 0;
}

inline void InitPlatform(platform_api *PlatformOut, platform_api PlatformIn) {
    PlatformOut->AddEntry = PlatformIn.AddEntry;
    PlatformOut->CompleteAllWork = PlatformIn.CompleteAllWork;
    PlatformOut->GetAllFilesOfTypeBegin = PlatformIn.GetAllFilesOfTypeBegin;
    PlatformOut->GetAllFilesOfTypeEnd = PlatformIn.GetAllFilesOfTypeEnd;
    PlatformOut->OpenNextFile = PlatformIn.OpenNextFile;
    PlatformOut->ReadDataFromFile = PlatformIn.ReadDataFromFile;
    PlatformOut->FileError = PlatformIn.FileError;
    // 指向临时存储的指针，用于存储短期的数据，如帧缓冲、临时计算等。
    PlatformOut->DEBUGPlatformReadEntireFile = PlatformIn.DEBUGPlatformReadEntireFile;
    PlatformOut->DEBUGPlatformFreeFileMemory = PlatformIn.DEBUGPlatformFreeFileMemory;
    PlatformOut->DEBUGPlatformWriteEntireFile = PlatformIn.DEBUGPlatformWriteEntireFile;
    PlatformOut->DEBUGPlatformExecuteSystemCommand = PlatformIn.DEBUGPlatformExecuteSystemCommand;
    PlatformOut->DEBUGPlatformCloseFileHandle = PlatformIn.DEBUGPlatformCloseFileHandle;
    PlatformOut->DEBUGPlatformGetProcessState = PlatformIn.DEBUGPlatformGetProcessState;
    PlatformOut->AllocateMemory = PlatformIn.AllocateMemory;
    PlatformOut->DeallocateMemory = PlatformIn.DeallocateMemory;
}

#define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Alignment) - 1))
#define Align4(Value) ((Value + 3) & ~3)
#define Align8(Value) ((Value + 7) & ~7)
#define Align16(Value) ((Value + 15) & ~15)
#endif